package com.company.cloud.product.modules.mgr.service.impl;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.company.cloud.common.asserts.ValidatorUtils;
import com.company.cloud.common.bean.LoginSimpleUserInfo;
import com.company.cloud.common.constant.BaseConstant.EnabledEnum;
import com.company.cloud.common.constant.BaseConstant.YNEnum;
import com.company.cloud.common.constant.BaseReturnEnum;
import com.company.cloud.common.exception.BusinessException;
import com.company.cloud.common.utils.AuthContextUtils;
import com.company.cloud.common.utils.CheckUtils;
import com.company.cloud.common.utils.StrSplitUtils;
import com.company.cloud.product.constant.ProductErrorEnum;
import com.company.cloud.product.modules.api.response.ProductSkuItem;
import com.company.cloud.product.modules.base.entity.ProductDisProfitConfig;
import com.company.cloud.product.modules.base.entity.ProductInfo;
import com.company.cloud.product.modules.base.entity.ProductStockInfo;
import com.company.cloud.product.modules.base.entity.SkuInfo;
import com.company.cloud.product.modules.base.entity.SpecificationInfo;
import com.company.cloud.product.modules.base.service.ProductDisProfitConfigService;
import com.company.cloud.product.modules.base.service.ProductInfoService;
import com.company.cloud.product.modules.base.service.ProductStockInfoService;
import com.company.cloud.product.modules.base.service.SkuInfoService;
import com.company.cloud.product.modules.base.service.SpecificationInfoService;
import com.company.cloud.product.modules.cache.service.ProductDisProfitCacheService;
import com.company.cloud.product.modules.cache.service.ProductInfoCacheService;
import com.company.cloud.product.modules.mgr.controller.req.ProductInfoSaveParam;
import com.company.cloud.product.modules.mgr.controller.req.ProductInfoUpdateParam;
import com.company.cloud.product.modules.mgr.controller.req.ProductRelInfoUpdateParam;
import com.company.cloud.product.modules.mgr.service.ProductMgrService;
import com.company.cloud.product.modules.mgr.utils.ProductSnUtils;
import com.company.common.server.constant.CloudConstant.ProductDisProfitTypeEnum;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;

@Service
public class ProductMgrServiceImpl implements ProductMgrService {

    @Autowired
    private ProductInfoService productInfoService;
    @Autowired
    private SkuInfoService skuInfoService;
    @Autowired
    private ProductStockInfoService productStockInfoService;
    @Autowired
    private ProductInfoCacheService productInfoCacheService;
    @Autowired
    private ProductDisProfitCacheService productDisProfitCacheService;
    @Autowired
    private ProductDisProfitConfigService productDisProfitConfigService;
    @Autowired
    private SpecificationInfoService specificationInfoService;

    private void validate(ProductInfoSaveParam param) {
        ValidatorUtils.validate(param);

        if (YNEnum.NO.getCode().equals(param.getIsDis())) {
            param.setDisProfitType(null);
            param.setDisProfitConfig(null);
        } else {
            if (StringUtils.isEmpty(param.getDisProfitType())) {
                throw new BusinessException(BaseReturnEnum.PARAM_NULL, "分润设置分类");
            }
            if (ProductDisProfitTypeEnum.PDPT_Custom.getCode().equals(param.getDisProfitType())) {
                if (param.getDisProfitConfig() == null) {
                    throw new BusinessException(BaseReturnEnum.PARAM_NULL, "分润设置");
                }
            }
        }

        if (YNEnum.YES.getCode().equals(param.getIsBuyLimit())) {
            if (!CheckUtils.hasInt(param.getBuyLimitNum())) {
                throw new BusinessException(BaseReturnEnum.PARAM_NULL, "限购数量");
            }
        }

    }


    /**
     * 新增商品引用
     */
    @Transactional
    @Override
    public ProductInfo addRel(String productNo, LoginSimpleUserInfo userInfo) {
        ProductInfo relProduct = productInfoService.getOne(new QueryWrapper<ProductInfo>()
                .eq("company_no", userInfo.getCompanyNo())
                .eq("main_product_no", productNo)
        );
        if (relProduct != null) {
            return relProduct;
        }

        ProductInfo product = productInfoService.getById(productNo);
        if (product == null || EnabledEnum.DISABLED.getCode().equals(product.getRowsState())) {
            throw new BusinessException(ProductErrorEnum.ProductInfo_NULL);
        }

        List<SkuInfo> skus = skuInfoService.list(new QueryWrapper<SkuInfo>()
                .eq("product_no", productNo));

        ProductInfo entity = new ProductInfo();
        BeanUtil.copyProperties(product, entity);
        entity.setCompanyNo(userInfo.getCompanyNo());
        entity.setMainCompanyNo(product.getCompanyNo());
        entity.setProductNo(ProductSnUtils.getProductSN());
        entity.setMainProductNo(product.getProductNo());
        entity.addCreateParam(userInfo);
        entity.addEditParam(userInfo);
        productInfoService.save(entity);

        if (!CollectionUtils.isEmpty(skus)) {
            List<SkuInfo> saveList = new ArrayList<SkuInfo>();
            skus.forEach(sku -> {
                SkuInfo model = new SkuInfo();
                BeanUtil.copyProperties(sku, model);
                model.setSkuNo(ProductSnUtils.getSkuSN());
                model.setMainSkuNo(sku.getSkuNo());
                model.setProductNo(entity.getProductNo());
                model.setCost(sku.getPrice());
                model.addCreateParam(userInfo);
                model.addEditParam(userInfo);
                saveList.add(model);
            });
            skuInfoService.saveBatch(saveList);
        }
        return entity;
    }

    /**
     * 新增商品
     */
    @Transactional
    @Override
    public ProductInfo save(ProductInfoSaveParam param, LoginSimpleUserInfo userInfo) {
        this.validate(param);
        String sn = ProductSnUtils.getProductSN();

        BigDecimal skuCost = null;
        BigDecimal skuMarketPrice = null;
        BigDecimal skuPrice = null;
        Integer skuRewardPoint = null;
        Integer skuExchangePoint = null;
//		Integer stockNum=null;
        //SKU
        if (!CollectionUtils.isEmpty(param.getSkuItems())) {//有SKU
            List<SkuInfo> skuList = new ArrayList<SkuInfo>();
            List<ProductStockInfo> stockList = new ArrayList<ProductStockInfo>();
            String isDef = null;
            for (ProductSkuItem skuItem : param.getSkuItems()) {
                SkuInfo sku = new SkuInfo();
                sku.setProductNo(sn);
                sku.setSkuNo(ProductSnUtils.getSkuSN(sn, skuItem.getItems()));
                sku.setMainSkuNo(sku.getSkuNo());
                sku.setImg(skuItem.getImg());
                if (!CollectionUtils.isEmpty(skuItem.getItems())) {
                    sku.setSpecificationValues(JSON.toJSONString(skuItem.getItems()));
                }
                sku.setCost(skuItem.getCost());
                sku.setMarketPrice(skuItem.getMarketPrice());
                sku.setPrice(skuItem.getPrice());
                if (StringUtils.isEmpty(skuItem.getIsDefault())) {
                    skuItem.setIsDefault(YNEnum.NO.getCode());
                }
                if (YNEnum.NO.getCode().equals(skuItem.getIsDefault())) {
                    sku.setIsDefault(skuItem.getIsDefault());
                } else {
                    if (isDef == null) {
                        sku.setIsDefault(YNEnum.YES.getCode());
                        isDef = YNEnum.YES.getCode();
                    } else {
                        sku.setIsDefault(YNEnum.NO.getCode());
                    }
                }
                sku.setExchangePoint(skuItem.getExchangePoint());
                sku.setRewardPoint(skuItem.getRewardPoint());
                sku.addCreateParam(userInfo);
                skuList.add(sku);

                if (skuItem.getStockNum() != null && skuItem.getStockNum().doubleValue() > 0) {
                    ProductStockInfo stockInfo = new ProductStockInfo();
                    stockInfo.setCompanyNo(param.getCompanyNo());
                    stockInfo.setCustNo(param.getCompanyNo());
                    stockInfo.setProductNo(sku.getProductNo());
                    stockInfo.setSkuNo(sku.getSkuNo());
                    stockInfo.setNum(skuItem.getStockNum());
                    stockInfo.setFreezeNum(BigDecimal.ZERO);
                    stockInfo.addCreateParam(userInfo);
                    stockInfo.addEditParam(userInfo);
                    stockList.add(stockInfo);
                }

                if (skuCost == null) {
                    skuCost = sku.getCost();
                } else {
                    skuCost = new BigDecimal(Math.min(sku.getCost().doubleValue(), skuCost.doubleValue()));
                }

                if (skuMarketPrice == null) {
                    skuMarketPrice = sku.getMarketPrice();
                } else {
                    skuMarketPrice = new BigDecimal(Math.min(sku.getMarketPrice().doubleValue(), skuMarketPrice.doubleValue()));
                }

                if (skuPrice == null) {
                    skuPrice = sku.getPrice();
                } else {
                    skuPrice = new BigDecimal(Math.min(sku.getPrice().doubleValue(), skuPrice.doubleValue()));
                }

                if (sku.getRewardPoint() != null) {
                    if (skuRewardPoint == null) {
                        skuRewardPoint = sku.getRewardPoint();
                    } else {
                        skuRewardPoint = Math.min(sku.getRewardPoint(), skuRewardPoint);
                    }
                }

                if (sku.getExchangePoint() != null) {
                    if (skuExchangePoint == null) {
                        skuExchangePoint = sku.getExchangePoint();
                    } else {
                        skuExchangePoint = Math.min(sku.getExchangePoint(), skuExchangePoint);
                    }
                }

            }
            skuInfoService.saveBatch(skuList);
            if (stockList.size() > 0) {
                productStockInfoService.saveBatch(stockList);
            }
        } else { //无SKU
            skuCost = param.getCost();
            skuMarketPrice = param.getMarketPrice();
            skuPrice = param.getPrice();
            skuRewardPoint = param.getRewardPoint();
            skuExchangePoint = param.getExchangePoint();
            SkuInfo sku = new SkuInfo();
            sku.setProductNo(sn);
            sku.setSkuNo(sn);
            sku.setMainSkuNo(sku.getSkuNo());
            sku.setCost(param.getCost());
            sku.setMarketPrice(param.getMarketPrice());
            sku.setPrice(param.getPrice());
            sku.setIsDefault(YNEnum.YES.getCode());
            sku.setExchangePoint(param.getExchangePoint());
            sku.setRewardPoint(param.getRewardPoint());
            sku.addCreateParam(userInfo);
            skuInfoService.save(sku);
            if (param.getStockNum() != null && param.getStockNum().doubleValue() > 0) {
                ProductStockInfo stockInfo = new ProductStockInfo();
                stockInfo.setCompanyNo(param.getCompanyNo());
                stockInfo.setCustNo(param.getCompanyNo());
                stockInfo.setProductNo(sku.getProductNo());
                stockInfo.setSkuNo(sku.getSkuNo());
                stockInfo.setNum(param.getStockNum());
                stockInfo.setFreezeNum(BigDecimal.ZERO);
                stockInfo.addCreateParam(userInfo);
                productStockInfoService.save(stockInfo);
            }
        }

        //product
        ProductInfo product = new ProductInfo();
        product.setProductNo(sn);
        product.setMainProductNo(product.getProductNo());
        product.setCompanyNo(param.getCompanyNo());
        product.setMainCompanyNo(product.getCompanyNo());
        product.setLangType(AuthContextUtils.getLang());
        product.setCategoryId(param.getCategoryId());
        product.setBrandId(param.getBrandId());
        product.setType(param.getType());
        product.setTreePath(param.getTreePath());
        product.setTwoType(param.getTwoType());
        product.setName(param.getName());
        product.setCaption(param.getCaption());
        product.setShareName(param.getShareName());
        product.setThirdProductUrl(param.getThirdProductUrl());
        product.setImage(param.getImage());
        product.setImage2(param.getImage2());
        product.setImage3(param.getImage3());
        product.setImage4(param.getImage4());
        product.setIntroduction(param.getIntroduction());
        product.setCost(skuCost != null ? skuCost : param.getCost());
        product.setMarketPrice(skuMarketPrice != null ? skuMarketPrice : param.getMarketPrice());
        product.setPrice(skuPrice != null ? skuPrice : param.getPrice());
        product.setExchangePoint(skuExchangePoint != null ? skuExchangePoint : param.getExchangePoint());
        product.setRewardPoint(skuRewardPoint != null ? skuRewardPoint : param.getRewardPoint());
        product.setUnit(param.getUnit());
        product.setWeight(param.getWeight());
        product.setLifeDay(param.getLifeDay());
        product.setMemo(param.getMemo());
        product.setIsMarketable(param.getIsMarketable());
        product.setIsExchangePurchase(StringUtils.isEmpty(param.getIsExchangePurchase()) ? YNEnum.YES.getCode() : param.getIsExchangePurchase());

        product.setIsDis(param.getIsDis());
        product.setDisProfitType(param.getDisProfitType());
        product.setIsBuyLimit(param.getIsBuyLimit());
        product.setBuyLimitNum(param.getBuyLimitNum());

        product.setIsAgent(param.getIsAgent());
        product.setAgentProfitType(param.getAgentProfitType());

        product.setOrders(param.getOrders());
        product.setKeyword(param.getKeyword());
        if (!CollectionUtils.isEmpty(param.getImageItems())) {
            product.setProductImages(JSON.toJSONString(param.getImageItems()));
        }
        if (!CollectionUtils.isEmpty(param.getSpecificationItems())) {
            product.setSpecificationItems(JSON.toJSONString(param.getSpecificationItems()));
        }
        if (!CollectionUtils.isEmpty(param.getTagItems())) {
            product.setTagValues(StrSplitUtils.list2string_prefix(param.getTagItems()));
        }
        product.setBizValue1(param.getBizValue1());
        product.setBizValue2(param.getBizValue2());
        product.setBizValue3(param.getBizValue3());
        product.setBizValue4(param.getBizValue4());
        product.setBizValue5(param.getBizValue5());
        product.setBizValue6(param.getBizValue6());
        product.setBizValue7(param.getBizValue7());
        product.setBizValue8(param.getBizValue8());
        product.setBizValue9(param.getBizValue9());

        product.setBizValue10(param.getBizValue10());
        product.setBizValue11(param.getBizValue11());
        product.setBizValue12(param.getBizValue12());
        product.setBizValue13(param.getBizValue13());
        product.setBizValue14(param.getBizValue14());
        product.setBizValue15(param.getBizValue15());
        product.setBizValue16(param.getBizValue16());
        product.setBizValue17(param.getBizValue17());
        product.setBizValue18(param.getBizValue18());
        product.setBizValue19(param.getBizValue19());
        product.setBizValue20(param.getBizValue20());
        product.setBizValue21(param.getBizValue21());
        product.setBizValue22(param.getBizValue22());
        product.setBizValue23(param.getBizValue23());
        product.setBizValue24(param.getBizValue24());
        product.setBizValue25(param.getBizValue25());
        product.setBizValue26(param.getBizValue26());
        product.setBizValue27(param.getBizValue27());
        product.setBizValue28(param.getBizValue28());

        product.setMetaKeywords(param.getMetaKeywords());
        product.setMetaDescription(param.getMetaDescription());

        product.setFreightFee(param.getFreightFee());
        product.setMounts(StrSplitUtils.list2string(param.getMounts()));
        product.setSaleNum(0);
        product.addCreateParam(userInfo);
        productInfoService.save(product);

        //分销设置
        if (param.getDisProfitConfig() != null) {
            ProductDisProfitConfig pdpc = new ProductDisProfitConfig();
            pdpc.setProductNo(product.getProductNo());
            pdpc.setCompanyNo(product.getCompanyNo());
            pdpc.setCalModel(param.getDisProfitConfig().getCalModel());
            pdpc.setDisValueOne(param.getDisProfitConfig().getDisValueOne());
            pdpc.setDisValueTwo(param.getDisProfitConfig().getDisValueTwo());
            pdpc.setDisValueThree(param.getDisProfitConfig().getDisValueThree());
            pdpc.addEditParam(userInfo);
            pdpc.addCreateParam(userInfo);
            productDisProfitConfigService.save(pdpc);
        }
        //规格
        List<SpecificationInfo> specificationList = new ArrayList<SpecificationInfo>();
        Set<String> specificationNames = new HashSet<String>();
        if (!CollectionUtils.isEmpty(param.getSpecificationItems())) {
            param.getSpecificationItems().forEach(item -> {
                SpecificationInfo specification = new SpecificationInfo();
                specification.setCompanyNo(product.getCompanyNo());
                specification.setName(item.getName());
                specification.setOptions(StrSplitUtils.list2string(item.getOptions()));
                specification.addCreateParam(userInfo);
                specification.addEditParam(userInfo);
                specificationList.add(specification);
                specificationNames.add(item.getName());
            });
        }
        if (specificationList.size() > 0) {
            specificationInfoService.remove(new QueryWrapper<SpecificationInfo>()
                    .eq("company_no", param.getCompanyNo())
                    .in("name", specificationNames));
            specificationInfoService.saveBatch(specificationList);
        }

        return product;
    }

    /**
     * 修改商品
     */
    @Transactional
    @Override
    public ProductInfo update(ProductInfoUpdateParam param, LoginSimpleUserInfo userInfo) {
        ProductInfo product = productInfoService.getById(param.getProductNo());
        if (product == null || EnabledEnum.DISABLED.getCode().equals(product.getRowsState())) {
            throw new BusinessException(ProductErrorEnum.ProductInfo_NULL);
        }
        if (YNEnum.YES.getCode().equals(product.getIsMarketable())) {
            throw new BusinessException(ProductErrorEnum.ProductInfo_UP_NotOp);
        }
        if (!product.getProductNo().equals(product.getMainProductNo())) {
            throw new BusinessException(ProductErrorEnum.ProductInfo_Rel_NotOp);
        }

        //删除SKU
        List<SkuInfo> oldSkuList = skuInfoService.list(new QueryWrapper<SkuInfo>()
                .eq("product_no", product.getProductNo()));
        Set<String> oldSkuNos = new HashSet<String>();
        if (!CollectionUtils.isEmpty(oldSkuList)) {
            oldSkuList.forEach(item -> {
                oldSkuNos.add(item.getSkuNo());
            });
            skuInfoService.removeByIds(oldSkuNos);
        }

        //库存
        List<ProductStockInfo> stockList = productStockInfoService.list(
                new QueryWrapper<ProductStockInfo>().eq("product_no", product.getMainProductNo()));
        Map<String, ProductStockInfo> stockMap = new HashMap<String, ProductStockInfo>();
        if (!CollectionUtils.isEmpty(stockList)) {
            productStockInfoService.update(new UpdateWrapper<ProductStockInfo>()
                    .set("rows_state", EnabledEnum.DISABLED.getCode())
                    .eq("product_no", product.getMainProductNo()));
            stockList.forEach(item -> {
                stockMap.put(item.getSkuNo(), item);
            });
        }


        BigDecimal skuCost = null;
        BigDecimal skuMarketPrice = null;
        BigDecimal skuPrice = null;
        Integer skuRewardPoint = null;
        Integer skuExchangePoint = null;
        //sku save
        if (!CollectionUtils.isEmpty(param.getSkuItems())) {
            List<SkuInfo> saveSkuList = new ArrayList<SkuInfo>();
            List<ProductStockInfo> saveStock = new ArrayList<ProductStockInfo>();
            List<ProductStockInfo> updateStock = new ArrayList<ProductStockInfo>();
            String isDef = null;
            for (ProductSkuItem skuItem : param.getSkuItems()) {
                String skuNo = ProductSnUtils.getSkuSN(product.getProductNo(), skuItem.getItems());
                SkuInfo sku = new SkuInfo();
                sku.setSkuNo(skuNo);
                sku.setProductNo(product.getProductNo());
                sku.setMainSkuNo(sku.getSkuNo());
                sku.setImg(skuItem.getImg());
                if (!CollectionUtils.isEmpty(skuItem.getItems())) {
                    sku.setSpecificationValues(JSON.toJSONString(skuItem.getItems()));
                }
                sku.setCost(skuItem.getCost());
                sku.setMarketPrice(skuItem.getMarketPrice());
                sku.setPrice(skuItem.getPrice());
                if (StringUtils.isEmpty(skuItem.getIsDefault())) {
                    skuItem.setIsDefault(YNEnum.NO.getCode());
                }
                if (YNEnum.NO.getCode().equals(skuItem.getIsDefault())) {
                    sku.setIsDefault(skuItem.getIsDefault());
                } else {
                    if (isDef == null) {
                        sku.setIsDefault(YNEnum.YES.getCode());
                        isDef = YNEnum.YES.getCode();
                    } else {
                        sku.setIsDefault(YNEnum.NO.getCode());
                    }
                }
                sku.setExchangePoint(skuItem.getExchangePoint());
                sku.setRewardPoint(skuItem.getRewardPoint());
                sku.addCreateParam(userInfo);
                saveSkuList.add(sku);

                if (skuCost == null) {
                    skuCost = sku.getCost();
                } else {
                    skuCost = new BigDecimal(Math.min(sku.getCost().doubleValue(), skuCost.doubleValue()));
                }

                if (skuMarketPrice == null) {
                    skuMarketPrice = sku.getMarketPrice();
                } else {
                    skuMarketPrice = new BigDecimal(Math.min(sku.getMarketPrice().doubleValue(), skuMarketPrice.doubleValue()));
                }

                if (skuPrice == null) {
                    skuPrice = sku.getPrice();
                } else {
                    skuPrice = new BigDecimal(Math.min(sku.getPrice().doubleValue(), skuPrice.doubleValue()));
                }

                if (sku.getRewardPoint() != null) {
                    if (skuRewardPoint == null) {
                        skuRewardPoint = sku.getRewardPoint();
                    } else {
                        skuRewardPoint = Math.min(sku.getRewardPoint(), skuRewardPoint);
                    }
                }

                if (sku.getExchangePoint() != null) {
                    if (skuExchangePoint == null) {
                        skuExchangePoint = sku.getExchangePoint();
                    } else {
                        skuExchangePoint = Math.min(sku.getExchangePoint(), skuExchangePoint);
                    }
                }
                //库存
                if (skuItem.getStockNum() != null && skuItem.getStockNum().doubleValue() > 0) {
                    ProductStockInfo stock = stockMap.get(sku.getSkuNo());
                    if (stock == null) {
                        stock = new ProductStockInfo();
                        stock.setCompanyNo(product.getCompanyNo());
                        stock.setCustNo(product.getCompanyNo());
                        stock.setProductNo(sku.getProductNo());
                        stock.setSkuNo(sku.getSkuNo());
                        stock.setNum(skuItem.getStockNum());
                        stock.setFreezeNum(BigDecimal.ZERO);
                        stock.addCreateParam(userInfo);
                        stock.addEditParam(userInfo);
                        saveStock.add(stock);
                    } else {
                        stock.setNum(skuItem.getStockNum());
                        stock.setRowsState(EnabledEnum.ENABLED.getCode());
                        updateStock.add(stock);
                    }
                }
            }
            skuInfoService.saveBatch(saveSkuList);
            if (saveStock.size() > 0) {
                productStockInfoService.saveBatch(saveStock);
            }
            if (updateStock.size() > 0) {
                productStockInfoService.updateBatchById(updateStock);
            }
        } else {
            skuCost = param.getCost();
            skuMarketPrice = param.getMarketPrice();
            skuPrice = param.getPrice();
            skuRewardPoint = param.getRewardPoint();
            skuExchangePoint = param.getExchangePoint();

            SkuInfo sku = new SkuInfo();
            sku.setProductNo(param.getProductNo());
            sku.setSkuNo(param.getProductNo());
            sku.setMainSkuNo(sku.getSkuNo());
            sku.setCost(param.getCost());
            sku.setMarketPrice(param.getMarketPrice());
            sku.setPrice(param.getPrice());
            sku.setIsDefault(YNEnum.YES.getCode());
            sku.setExchangePoint(param.getExchangePoint());
            sku.setRewardPoint(param.getRewardPoint());
            sku.addCreateParam(userInfo);
            skuInfoService.save(sku);
            //库存
            if (param.getStockNum() != null && param.getStockNum().doubleValue() > 0) {
                ProductStockInfo stock = stockMap.get(sku.getSkuNo());
                if (stock == null) {
                    stock = new ProductStockInfo();
                    stock.setCompanyNo(product.getCompanyNo());
                    stock.setCustNo(product.getCompanyNo());
                    stock.setProductNo(sku.getProductNo());
                    stock.setSkuNo(sku.getSkuNo());
                    stock.setNum(param.getStockNum());
                    stock.setFreezeNum(BigDecimal.ZERO);
                    stock.addCreateParam(userInfo);
                    stock.addEditParam(userInfo);
                    productStockInfoService.save(stock);
                } else {
                    stock.setNum(param.getStockNum());
                    stock.setRowsState(EnabledEnum.ENABLED.getCode());
                    productStockInfoService.updateById(stock);
                }
            }
        }

        //update
        if (StrUtil.isNotEmpty(param.getCompanyNo())) {
            product.setCompanyNo(param.getCompanyNo());
            product.setMainCompanyNo(param.getCompanyNo());
        }
        product.setCategoryId(param.getCategoryId());
        product.setBrandId(param.getBrandId());
        product.setType(param.getType());
        product.setTwoType(param.getTwoType());
        product.setName(param.getName());
        product.setCaption(param.getCaption());
        product.setTreePath(param.getTreePath());
        product.setShareName(param.getShareName());
        product.setThirdProductUrl(param.getThirdProductUrl());
        product.setImage(param.getImage());
        product.setImage2(param.getImage2());
        product.setImage3(param.getImage3());
        product.setImage4(param.getImage4());
        product.setIntroduction(param.getIntroduction());
        product.setCost(skuCost != null ? skuCost : param.getCost());
        product.setMarketPrice(skuMarketPrice != null ? skuMarketPrice : param.getMarketPrice());
        product.setPrice(skuPrice != null ? skuPrice : param.getPrice());
        product.setExchangePoint(skuExchangePoint != null ? skuExchangePoint : param.getExchangePoint());
        product.setRewardPoint(skuRewardPoint != null ? skuRewardPoint : param.getRewardPoint());
        product.setUnit(param.getUnit());
        product.setWeight(param.getWeight());
        product.setLifeDay(param.getLifeDay());
        product.setMemo(param.getMemo());
        product.setIsExchangePurchase(StringUtils.isEmpty(param.getIsExchangePurchase()) ? YNEnum.YES.getCode() : param.getIsExchangePurchase());

        product.setIsDis(param.getIsDis());
        product.setDisProfitType(param.getDisProfitType());

        product.setIsAgent(param.getIsAgent());
        product.setAgentProfitType(param.getAgentProfitType());
        product.setIsBuyLimit(param.getIsBuyLimit());
        product.setBuyLimitNum(param.getBuyLimitNum());

        product.setIsMarketable(param.getIsMarketable());
        product.setOrders(param.getOrders());
        product.setKeyword(param.getKeyword());

        if (!CollectionUtils.isEmpty(param.getImageItems())) {
            product.setProductImages(JSON.toJSONString(param.getImageItems()));
        } else {
            product.setProductImages(null);
        }
        if (!CollectionUtils.isEmpty(param.getSpecificationItems())) {
            product.setSpecificationItems(JSON.toJSONString(param.getSpecificationItems()));
        } else {
            product.setSpecificationItems(null);
        }
        if (!CollectionUtils.isEmpty(param.getTagItems())) {
            product.setTagValues(StrSplitUtils.list2string_prefix(param.getTagItems()));
        } else {
            product.setTagValues(null);
        }
        product.setBizValue1(param.getBizValue1());
        product.setBizValue2(param.getBizValue2());
        product.setBizValue3(param.getBizValue3());
        product.setBizValue4(param.getBizValue4());
        product.setBizValue5(param.getBizValue5());
        product.setBizValue6(param.getBizValue6());
        product.setBizValue7(param.getBizValue7());
        product.setBizValue8(param.getBizValue8());
        product.setBizValue9(param.getBizValue9());
        product.setBizValue10(param.getBizValue10());
        product.setBizValue11(param.getBizValue11());
        product.setBizValue12(param.getBizValue12());
        product.setBizValue13(param.getBizValue13());
        product.setBizValue14(param.getBizValue14());
        product.setBizValue15(param.getBizValue15());
        product.setBizValue16(param.getBizValue16());
        product.setBizValue17(param.getBizValue17());
        product.setBizValue18(param.getBizValue18());
        product.setBizValue19(param.getBizValue19());
        product.setBizValue20(param.getBizValue20());

        product.setBizValue21(param.getBizValue21());
        product.setBizValue22(param.getBizValue22());
        product.setBizValue23(param.getBizValue23());
        product.setBizValue24(param.getBizValue24());
        product.setBizValue25(param.getBizValue25());
        product.setBizValue26(param.getBizValue26());
        product.setBizValue27(param.getBizValue27());
        product.setBizValue28(param.getBizValue28());
        product.setMetaKeywords(param.getMetaKeywords());
        product.setMetaDescription(param.getMetaDescription());
        product.setFreightFee(param.getFreightFee());
        product.setMounts(StrSplitUtils.list2string(param.getMounts()));
        product.addEditParam(userInfo);
        product.setEdt(LocalDateTime.now());
        productInfoService.updateById(product);

        //库存
//		stockMap

        //分销设置
        productDisProfitConfigService.removeById(product.getProductNo());
        if (param.getDisProfitConfig() != null) {
            ProductDisProfitConfig pdpc = new ProductDisProfitConfig();
            pdpc.setProductNo(product.getProductNo());
            pdpc.setCompanyNo(product.getCompanyNo());
            pdpc.setCalModel(param.getDisProfitConfig().getCalModel());
            pdpc.setDisValueOne(param.getDisProfitConfig().getDisValueOne());
            pdpc.setDisValueTwo(param.getDisProfitConfig().getDisValueTwo());
            pdpc.setDisValueThree(param.getDisProfitConfig().getDisValueThree());
            pdpc.addEditParam(userInfo);
            pdpc.addCreateParam(userInfo);
            productDisProfitConfigService.save(pdpc);
        }

        //规格
        List<SpecificationInfo> specificationList = new ArrayList<SpecificationInfo>();
        Set<String> specificationNames = new HashSet<String>();
        if (!CollectionUtils.isEmpty(param.getSpecificationItems())) {
            param.getSpecificationItems().forEach(item -> {
                SpecificationInfo specification = new SpecificationInfo();
                specification.setCompanyNo(userInfo.getCompanyNo());
                specification.setName(item.getName());
                specification.setOptions(StrSplitUtils.list2string(item.getOptions()));
                specification.addCreateParam(userInfo);
                specification.addEditParam(userInfo);
                specificationList.add(specification);
                specificationNames.add(item.getName());
            });
        }
        if (specificationList.size() > 0) {
            specificationInfoService.remove(new QueryWrapper<SpecificationInfo>()
                    .eq("company_no", userInfo.getCompanyNo())
                    .in("name", specificationNames));
            specificationInfoService.saveBatch(specificationList);
        }


        //
        productInfoCacheService.removeProductByNoByCache(product.getProductNo());
        productDisProfitCacheService.removeProductDisProfit(product.getProductNo());
        if (oldSkuNos.size() > 0) {
            productInfoCacheService.removeSku(oldSkuNos);
        }
        return product;
    }


    /**
     * 修改引用商品
     */
    @Transactional
    @Override
    public ProductInfo updateRel(ProductRelInfoUpdateParam param, LoginSimpleUserInfo userInfo) {
        ProductInfo product = productInfoService.getById(param.getProductNo());
        if (product == null || EnabledEnum.DISABLED.getCode().equals(product.getRowsState())) {
            throw new BusinessException(ProductErrorEnum.ProductInfo_NULL);
        }
        if (YNEnum.YES.getCode().equals(product.getIsMarketable())) {
            throw new BusinessException(ProductErrorEnum.ProductInfo_UP_NotOp);
        }
        if (product.getProductNo().equals(product.getMainProductNo())) {
            throw new BusinessException(ProductErrorEnum.ProductInfo_NotRel_NotOp);
        }
        //SKU
        List<SkuInfo> oldSkuList = skuInfoService.list(new QueryWrapper<SkuInfo>().eq("product_no", product.getProductNo()));
        Set<String> oldSkuNos = new HashSet<String>();
        Map<String, SkuInfo> oldSkuMap = new HashMap<String, SkuInfo>();
        if (!CollectionUtils.isEmpty(oldSkuList)) {
            oldSkuList.forEach(item -> {
                oldSkuNos.add(item.getSkuNo());
                oldSkuMap.put(item.getSkuNo(), item);
            });
        }

        BigDecimal skuCost = null;
        BigDecimal skuMarketPrice = null;
        BigDecimal skuPrice = null;
        Integer skuRewardPoint = null;
        Integer skuExchangePoint = null;
        //sku save
        if (!CollectionUtils.isEmpty(param.getSkuItems())) {
            List<SkuInfo> updateSkuList = new ArrayList<SkuInfo>();
            String isDef = null;
            for (ProductSkuItem skuItem : param.getSkuItems()) {
                if (StringUtils.isEmpty(skuItem.getSkuNo())) {
                    throw new BusinessException(ProductErrorEnum.SkuInfo_NULL);
                }
                SkuInfo sku = oldSkuMap.get(skuItem.getSkuNo());
                if (sku == null) {
                    throw new BusinessException(ProductErrorEnum.SkuInfo_NULL);
                }
                sku.setCost(skuItem.getCost());
                sku.setMarketPrice(skuItem.getMarketPrice());
                sku.setPrice(skuItem.getPrice());
                if (StringUtils.isEmpty(skuItem.getIsDefault())) {
                    skuItem.setIsDefault(YNEnum.NO.getCode());
                } else if (YNEnum.NO.getCode().equals(skuItem.getIsDefault())) {
                    sku.setIsDefault(skuItem.getIsDefault());
                } else {
                    if (isDef == null) {
                        sku.setIsDefault(YNEnum.YES.getCode());
                        isDef = YNEnum.YES.getCode();
                    } else {
                        sku.setIsDefault(YNEnum.NO.getCode());
                    }
                }
                sku.setExchangePoint(skuItem.getExchangePoint());
                sku.setRewardPoint(skuItem.getRewardPoint());
                sku.addCreateParam(userInfo);
                updateSkuList.add(sku);
                if (skuCost == null) {
                    skuCost = sku.getCost();
                } else {
                    skuCost = new BigDecimal(Math.min(sku.getCost().doubleValue(), skuCost.doubleValue()));
                }
                if (skuMarketPrice == null) {
                    skuMarketPrice = sku.getMarketPrice();
                } else {
                    skuMarketPrice = new BigDecimal(Math.min(sku.getMarketPrice().doubleValue(), skuMarketPrice.doubleValue()));
                }
                if (skuPrice == null) {
                    skuPrice = sku.getPrice();
                } else {
                    skuPrice = new BigDecimal(Math.min(sku.getPrice().doubleValue(), skuPrice.doubleValue()));
                }

                if (sku.getRewardPoint() != null) {
                    if (skuRewardPoint == null) {
                        skuRewardPoint = sku.getRewardPoint();
                    } else {
                        skuRewardPoint = Math.min(sku.getRewardPoint(), skuRewardPoint);
                    }
                }

                if (sku.getExchangePoint() != null) {
                    if (skuExchangePoint == null) {
                        skuExchangePoint = sku.getExchangePoint();
                    } else {
                        skuExchangePoint = Math.min(sku.getExchangePoint(), skuExchangePoint);
                    }
                }
            }
            skuInfoService.updateBatchById(updateSkuList);
        } else {
            skuCost = param.getCost();
            skuMarketPrice = param.getMarketPrice();
            skuPrice = param.getPrice();
            skuRewardPoint = param.getRewardPoint();
            skuExchangePoint = param.getExchangePoint();


            SkuInfo sku = oldSkuMap.get(param.getProductNo());
            if (sku == null) {
                throw new BusinessException("");
            }
            sku.setCost(param.getCost());
            sku.setMarketPrice(param.getMarketPrice());
            sku.setPrice(param.getPrice());
            sku.setIsDefault(YNEnum.YES.getCode());
            sku.setExchangePoint(param.getExchangePoint());
            sku.setRewardPoint(param.getRewardPoint());
            sku.addCreateParam(userInfo);
            skuInfoService.updateById(sku);
        }

        //update
        product.setCategoryId(param.getCategoryId());
        product.setBrandId(param.getBrandId());
        product.setType(param.getType());
        product.setTwoType(param.getTwoType());
        product.setName(param.getName());
        product.setCaption(param.getCaption());
        product.setShareName(param.getShareName());
        product.setImage(param.getImage());
        product.setImage2(param.getImage2());
        product.setImage3(param.getImage3());
        product.setImage4(param.getImage4());
        product.setIntroduction(param.getIntroduction());
        product.setCost(skuCost != null ? skuCost : param.getCost());
        product.setMarketPrice(skuMarketPrice != null ? skuMarketPrice : param.getMarketPrice());
        product.setPrice(skuPrice != null ? skuPrice : param.getPrice());
        product.setExchangePoint(skuExchangePoint != null ? skuExchangePoint : param.getExchangePoint());
        product.setRewardPoint(skuRewardPoint != null ? skuRewardPoint : param.getRewardPoint());
        product.setUnit(param.getUnit());
        product.setWeight(param.getWeight());
        product.setLifeDay(param.getLifeDay());
        product.setMemo(param.getMemo());
        product.setIsExchangePurchase(StringUtils.isEmpty(param.getIsExchangePurchase()) ? YNEnum.YES.getCode() : param.getIsExchangePurchase());
        product.setIsDis(param.getIsDis());
        product.setDisProfitType(param.getDisProfitType());
        product.setIsBuyLimit(param.getIsBuyLimit());
        product.setBuyLimitNum(param.getBuyLimitNum());

        product.setIsMarketable(param.getIsMarketable());
        product.setOrders(param.getOrders());
        product.setKeyword(param.getKeyword());

        if (!CollectionUtils.isEmpty(param.getImageItems())) {
            product.setProductImages(JSON.toJSONString(param.getImageItems()));
        } else {
            product.setProductImages(null);
        }
        if (!CollectionUtils.isEmpty(param.getTagItems())) {
            product.setTagValues(StrSplitUtils.list2string_prefix(param.getTagItems()));
        } else {
            product.setTagValues(null);
        }
        product.setBizValue1(param.getBizValue1());
        product.setBizValue2(param.getBizValue2());
        product.setBizValue3(param.getBizValue3());
        product.setBizValue4(param.getBizValue4());
        product.setBizValue5(param.getBizValue5());
        product.setBizValue6(param.getBizValue6());
        product.setBizValue7(param.getBizValue7());
        product.setBizValue8(param.getBizValue8());
        product.setBizValue9(param.getBizValue9());

        product.setBizValue10(param.getBizValue10());
        product.setBizValue11(param.getBizValue11());
        product.setBizValue12(param.getBizValue12());
        product.setBizValue13(param.getBizValue13());
        product.setBizValue14(param.getBizValue14());
        product.setBizValue15(param.getBizValue15());
        product.setBizValue16(param.getBizValue16());
        product.setBizValue17(param.getBizValue17());
        product.setBizValue18(param.getBizValue18());
        product.setBizValue19(param.getBizValue19());
        product.setBizValue20(param.getBizValue20());

        product.setBizValue21(param.getBizValue21());
        product.setBizValue22(param.getBizValue22());
        product.setBizValue23(param.getBizValue23());
        product.setBizValue24(param.getBizValue24());
        product.setBizValue25(param.getBizValue25());
        product.setBizValue26(param.getBizValue26());
        product.setBizValue27(param.getBizValue27());
        product.setBizValue28(param.getBizValue28());

        product.setMetaKeywords(param.getMetaKeywords());
        product.setMetaDescription(param.getMetaDescription());

        product.setFreightFee(param.getFreightFee());
        product.setMounts(StrSplitUtils.list2string(param.getMounts()));


        product.addEditParam(userInfo);
        productInfoService.updateById(product);

        //分销设置
        productDisProfitConfigService.remove(new QueryWrapper<ProductDisProfitConfig>()
                .eq("product_no", product.getProductNo()));
        if (param.getDisProfitConfig() != null) {
            ProductDisProfitConfig pdpc = new ProductDisProfitConfig();
            pdpc.setProductNo(product.getProductNo());
            pdpc.setCompanyNo(product.getCompanyNo());
            pdpc.setCalModel(param.getDisProfitConfig().getCalModel());
            pdpc.setDisValueOne(param.getDisProfitConfig().getDisValueOne());
            pdpc.setDisValueTwo(param.getDisProfitConfig().getDisValueTwo());
            pdpc.setDisValueThree(param.getDisProfitConfig().getDisValueThree());
            pdpc.addEditParam(userInfo);
            pdpc.addCreateParam(userInfo);
            productDisProfitConfigService.save(pdpc);
        }

        productInfoCacheService.removeProductByNoByCache(product.getProductNo());
        productDisProfitCacheService.removeProductDisProfit(product.getProductNo());
        if (oldSkuNos.size() > 0) {
            productInfoCacheService.removeSku(oldSkuNos);
        }
        return product;
    }

    @Transactional
    @Override
    public ProductInfo delete(String productNo, LoginSimpleUserInfo userInfo) {
        ProductInfo entity = productInfoService.getById(productNo);
        if (entity == null || EnabledEnum.DISABLED.getCode().equals(entity.getRowsState())) {
            throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
        }
        if (YNEnum.YES.getCode().equals(entity.getIsMarketable())) {
            throw new BusinessException(ProductErrorEnum.ProductInfo_UP_NotOp);
        }
        entity.setRowsState(EnabledEnum.DISABLED.getCode());
        entity.addEditParam(userInfo);
        productInfoService.updateById(entity);
        productStockInfoService.remove(new QueryWrapper<ProductStockInfo>()
                .eq("product_no", entity.getProductNo()));
        return entity;
    }


}
